// pages/players/players.js
const playersStore = require('../../stores/players')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    players: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setPlayers()
  },

  setPlayers() {
    const players = Object.values(playersStore.getPlayers());
    this.setData({
      players,
      noPlayer: players.length === 0,
    })
  },

  handleAdd() {
    const addPlayerComp = this.selectComponent('#add-player');
    addPlayerComp.clearFormData()
    this.setData({ show: true })
  },

  handleCancel() {
    this.setData({ show: false })
  },

  handleChangePlayer(event) {
    const addPlayerComp = this.selectComponent('#add-player');
    const player = event.detail;
    if (!player.playerNum) {
      playersStore.addPlayer(player);
    } else {
      playersStore.editPlayer(player);
    }
    addPlayerComp.clearFormData();
    this.setPlayers()
    this.setData({ show: false })
  },

  handleEditPlayer(event) {
    const player = event.target.dataset.item;
    const addPlayerComp = this.selectComponent('#add-player');
    addPlayerComp.setEditPlayerInfo(player);
    this.setData({
      show: true,
    })
  }
})